#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/20 11:33
# @Author  : Samge
import json
import os
import sys
import time

from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget

from itkz.resources.utils import file_util, config_util
from itkz.resources.view_area_selected import Ui_Form


class AreaWidget(QWidget, Ui_Form):

    # 本地省市区信息的json
    JSON_PATH = '../configs/area_info.json'

    # 省市区信息
    area_infos = None

    # 当前选中的城市列表
    curr_citys = None

    # 当前选中的信息
    curr_selected_info = None

    # 默认提示文字
    DEFAULT_TEXT = '请选择'

    # 筛选字段key名
    fields_key = {}

    # 配置名
    settingsName = ''

    # 声明带一个str类型参数的信号, 这里定义的信号对象名跟使用着的信号名无关, 跟发送出去的参数类型跟数量有关 20210722 目前是这样理解的
    signal_selected = pyqtSignal(str)

    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.setupData()

    def get_names(self, lst):
        lst = ['%s' % item.get('name') if type(item) is dict else item for item in lst]
        lst.insert(0, self.DEFAULT_TEXT)
        return lst

    def get_province_names(self):
        return self.get_names(self.area_infos)

    def get_city_names(self, province):
        if not province or self.DEFAULT_TEXT == province:
            return [self.DEFAULT_TEXT]
        for item in self.area_infos:
            if province == item.get('name'):
                self.curr_citys = item.get('city') or []
                return self.get_names(self.curr_citys)
        return [self.DEFAULT_TEXT]

    def get_area_names(self, city):
        if not city or self.DEFAULT_TEXT == city:
            return [self.DEFAULT_TEXT]
        for item in self.curr_citys:
            if city == item.get('name'):
                return self.get_names(item.get('area'))
        return [self.DEFAULT_TEXT]

    def setupData(self):
        os.chdir(file_util.get_parent_path(__file__))
        self.area_infos = json.loads(file_util.read_txt_file(self.JSON_PATH)) or []
        self.cb_province.addItems(self.get_province_names())

    def text_change_province(self, v):
        print(f'text_change_province {v}')
        self.cb_city.clear()
        self.cb_city.addItems(self.get_city_names(v))

    def text_change_city(self, v):
        print(f'text_change_city {v}')
        self.cb_area.clear()
        self.cb_area.addItems(self.get_area_names(v))

    def text_change_area(self, v):
        print(f'text_change_area {v}')
        selected_info = json.dumps(self.get_data(), ensure_ascii=False)
        if v and self.curr_selected_info != selected_info:
            self.curr_selected_info = selected_info
            self.signal_selected.emit(selected_info)

    # 可在外部与槽函数连接
    def onSelectedListener(self, func):
        self.signal_selected.connect(func)

    def currentText(self, _cb):
        txt = _cb.currentText().replace(' ', '').replace('其他', '')
        return txt if self.DEFAULT_TEXT != txt else ''

    def currentProvinceFull(self):
        return self.currentText(self.cb_province) or ''

    def currentProvince(self):
        return self.currentProvinceFull().replace('省', '').replace('市', '')

    def currentCity(self):
        return self.currentText(self.cb_city) or ''

    def currentArea(self):
        return self.currentText(self.cb_area) or ''

    def get_data(self, need_code=True):
        province_full = self.currentProvinceFull()
        city = self.currentCity()
        area = self.currentArea()
        area_info = {
            'province_full': province_full,
            'province': self.currentProvince(),
            'city': city,
            'area': area
        }
        if need_code:
            area_info['code'] = self.get_area_code(province_full, city, area)
        return area_info

    def get_area_code(self, province_full, city, area):
        """
        读取区域码信息
        :param province_full:
        :param city:
        :param area:
        :return:
        """
        if not self.area_infos or not province_full:
            return ''
        for province_item in self.area_infos or []:
            if province_full != province_item.get('name'):
                continue
            if not city and not area:
                return province_item.get('code')

            for city_item in province_item.get('city') or []:
                if city != city_item.get('name'):
                    continue
                if not area:
                    return city_item.get('code')

                for area_item in city_item.get('area') or []:
                    if area == area_item.get('name'):
                        return area_item.get('code')

    def setupQSettingsName(self, name):
        self.settingsName = name

    def setupFieldsKey(self, fields_key):
        self.fields_key = fields_key
        self.init_config_value()

    def init_config_value(self):
        self.cb_province.setCurrentIndex(int(config_util.value(f"{self.settingsName}/province_index_value") or 0))
        self.cb_city.setCurrentIndex(int(config_util.value(f"{self.settingsName}/city_index_value") or 0))
        self.cb_area.setCurrentIndex(int(config_util.value(f"{self.settingsName}/area_index_value") or 0))

    def save_config_value(self):
        config_util.setValue(f"{self.settingsName}/province_index_value", self.cb_province.currentIndex() or 0)
        config_util.setValue(f"{self.settingsName}/city_index_value", self.cb_city.currentIndex() or 0)
        config_util.setValue(f"{self.settingsName}/area_index_value", self.cb_area.currentIndex() or 0)

    def set_custom_query_data(self, query_data):
        self.cb_province.setCurrentText(query_data.get('province_full') or '')
        self.cb_city.setCurrentText(query_data.get('city') or '')
        self.cb_area.setCurrentText(query_data.get('area') or '')


def main():
    app = QtWidgets.QApplication(sys.argv)
    gui = AreaWidget()
    gui.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
